<template>
	<view class="container">
		
		<!-- 搜索栏 -->
		<view class="search-section">
			<view class="search-box">
				<text class="search-icon">🔍</text>
				<input 
					v-model="searchKeyword" 
					placeholder="搜索备件编号或名称"
					@input="onSearchInput"
					class="search-input"
				/>
				<text v-if="searchKeyword" class="clear-icon" @click="clearSearch">✕</text>
			</view>
			<view class="action-btn add-part-btn" @click="goAdd">
					<text class="btn-icon">+</text>
			</view>
		</view>
		
		<!-- 备件卡片列表 -->
		<view class="parts-list">
			<view 
				v-for="(item, index) in spareParts" 
				:key="index" 
				class="part-card" 
				@click="viewDetail(item)"
			>
			<!-- 左侧图片 -->
			<view class="card-image">
				<image 
					:src="getPartImage(item)" 
					mode="aspectFill"
					class="part-img"
					@error="handleImageError"
				/>
			</view>
				
				<!-- 右侧信息 -->
				<view class="card-content">
					<!-- 备件名称 -->
					<view class="card-title">{{ item.name }}</view>
					
					<!-- 备件信息 -->
					<view class="card-info">
						<view class="info-row">
							<text class="info-label">备件编号：</text>
							<text class="info-value">{{ item.partNo }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">备件类型：</text>
							<text class="info-value">{{ item.type }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">库存数量：</text>
							<text class="info-value stock-value">{{ item.totalStock }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-if="!isRefreshing && spareParts.length === 0">
			<text class="empty-icon">📦</text>
			<view class="empty-text">暂无备件数据</view>
			<button class="empty-btn" @click="manualRefresh">刷新数据</button>
		</view>

		<!-- 加载状态 -->
		<view class="loading-state" v-if="isRefreshing">
			<text class="loading-text">加载中...</text>
		</view>
	</view>
</template>

<script>
import { listPartDTO, delPart } from '@/api/inventory/part.js';
import { getDicts } from '@/api/dict/data.js';
import { listTransaction } from '@/api/inventory/transaction.js';
import { listPartType } from '@/api/inventory/partType.js';

export default {
	data() {
		return {
			searchKeyword: '',
			spareParts: [],
			statusDict: [],
			partTypeOptions: [],
			debounceTimer: null,
			isRefreshing: false,
			typeMapping: {
				'BEARING': '轴承',
				'SEAL': '密封件',
				'FILTER': '过滤器',
				'BELT': '皮带',
				'CHAIN': '链条',
				'GEAR': '齿轮',
				'MOTOR': '电机',
				'PUMP': '泵',
				'VALVE': '阀门',
				'SENSOR': '传感器',
				'CONTROLLER': '控制器',
				'SWITCH': '开关',
				'CABLE': '电缆',
				'CONNECTOR': '连接器',
				'BOLT': '螺栓',
				'NUT': '螺母',
				'WASHER': '垫圈',
				'SPRING': '弹簧',
				'BUSHING': '衬套',
				'GASKET': '垫片'
			},
			// 备件类型图标映射
			partIcons: {
				'轴承': '⚙️',
				'密封件': '🔒',
				'过滤器': '🧹',
				'皮带': '⛓️',
				'链条': '🔗',
				'齿轮': '⚙️',
				'电机': '⚡',
				'泵': '💧',
				'阀门': '🚰',
				'传感器': '📡',
				'控制器': '🎛️',
				'开关': '🔌',
				'电缆': '🔌',
				'连接器': '🔗',
				'螺栓': '🔩',
				'螺母': '🔩',
				'垫圈': '⭕',
				'弹簧': '🌀',
				'衬套': '⭕',
				'垫片': '⭕',
				'设备': '🔧',
				'未知': '📦'
			}
		};
	},
	onLoad() {
		this.loadDicts();
		this.loadPartTypes();
		this.fetchList();
	},
	onShow() {
		// 检查是否需要刷新数据
		const needRefresh = uni.getStorageSync('needRefreshLedger');
		if (needRefresh) {
			uni.removeStorageSync('needRefreshLedger');
			this.fetchList();
		}
	},
	methods: {
		// 加载备件类型字典
		async loadPartTypes() {
			try {
				const response = await listPartType({ enabled: 1 });
				if (response.code === 200 && response.rows) {
					this.partTypeOptions = response.rows;
				}
			} catch (error) {
				console.error('加载备件类型字典失败:', error);
			}
		},
		
		// 获取备件类型中文名称
		getPartTypeName(code) {
			if (!code) return '未知';
			const partType = this.partTypeOptions.find(item => item.code === code);
			return partType ? partType.name : this.getTypeName(code);
		},
		
		// 获取备件真实图片
		getPartImage(item) {
			// 优先使用item中的图片URL
			if (item.imageUrl) {
				const imageUrl = Array.isArray(item.imageUrl) ? item.imageUrl[0] : item.imageUrl;
				if (imageUrl) {
					// 如果是完整URL，直接返回
					if (/^https?:\/\//i.test(imageUrl)) {
						return imageUrl;
					}
					// 否则构建MinIO URL
					const minioBase = uni.getStorageSync('MINIO_BASE') || 'https://io.brightholdings.cn';
					const bucket = 'smart-maintenance';
					return `${minioBase.replace(/\/$/, '')}/${bucket}/${imageUrl}`;
				}
			}
			
			// 如果没有图片，使用占位图
			return '/static/images/default-part.png';
		},
		
		// 图片加载失败处理
		handleImageError(e) {
			console.log('图片加载失败:', e);
			// 图片加载失败时，可以设置默认图片
			e.target.src = '/static/images/default-part.png';
		},
		
		// 直接API调用的库存计算
		async fetchList() {
			try {
				// 步骤1: 获取备件基础信息
				const partResponse = await listPartDTO({});
				const parts = partResponse.rows || partResponse.data || [];
				
				if (parts.length === 0) {
					this.spareParts = [];
					return Promise.resolve();
				}
				
				// 步骤2: 获取所有交易记录
				const transactionResponse = await listTransaction({
					pageNum: 1,
					pageSize: 1000,
					params: {
						txType: 'REPAIR,TRANSFER,MAINTENANCE,SCRAP,OTHER,INBOUND,OUTBOUND,PURCHASE'
					}
				});
				
				const transactions = transactionResponse.rows || transactionResponse.data || [];
				
				// 步骤3: 初始化库存计算
				const partInventory = {};
				
				// 先用备件基础信息初始化
				parts.forEach(part => {
					const partNo = part.partNo || part.part_no;
					if (!partNo) return;
					
					// 处理图片URL
					let imageUrl = null;
					if (part.imageUrls) {
						try {
							const images = typeof part.imageUrls === 'string' ? JSON.parse(part.imageUrls) : part.imageUrls;
							imageUrl = Array.isArray(images) && images.length > 0 ? images[0] : images;
						} catch (e) {
							console.error('解析图片URL失败:', e);
						}
					}
					
					partInventory[partNo] = {
						partNo: partNo,
						name: part.partName || part.name || `备件${partNo}`,
						type: part.partTypeCode || part.partType || part.part_type || '未知类型', // 使用partTypeCode
						warehouseCode: part.warehouseCode || 'WH001',
						imageUrl: imageUrl,
						specNo: part.specNo || '',
						stockTotal: part.stockTotal || 0, // 直接使用API返回的库存总数
						inboundTotal: 0,
						outboundTotal: 0,
						netStock: 0,
						transactions: []
					};
				});
				
				// 步骤4: 遍历交易明细更新库存
				transactions.forEach((transaction, txIndex) => {
					const items = transaction.transactionItems || [];
					const txNo = transaction.txNo || `交易${txIndex + 1}`;
					
					items.forEach(item => {
						const partNo = item.partNo || item.part_no;
						const quantity = parseFloat(item.quantity) || 0;
						const direction = (item.direction || '').toUpperCase();
						
						if (!partNo || quantity <= 0) {
							return;
						}
						
						if (!partInventory[partNo]) {
							return;
						}
						
						const entry = partInventory[partNo];
						
						// 入库
						if (direction === 'IN' || direction === 'INBOUND' || direction === 'PURCHASE') {
							entry.inboundTotal += quantity;
							entry.netStock += quantity;
						}
						// 出库
						else if (direction === 'OUT' || direction === 'OUTBOUND' || 
								  direction === 'REPAIR' || direction === 'TRANSFER' || 
								  direction === 'SCRAP' || direction === 'MAINTENANCE') {
							entry.outboundTotal += quantity;
							entry.netStock -= quantity;
						}
						
						// 记录交易
						entry.transactions.push({
							txNo: txNo,
							direction: direction,
							quantity: quantity,
							date: transaction.createdAt || transaction.created_at
						});
					});
				});
				
				// 步骤5: 格式化最终数据
				const spareParts = Object.values(partInventory).map(part => {
					// 使用API返回的真实库存数量
					const displayStock = part.stockTotal || 0;
					
					return {
						id: part.partNo,
						name: part.name,
						partNo: part.partNo,
						type: this.getPartTypeName(part.type), // 将类型代码映射为中文名称
						warehouseCode: part.warehouseCode,
						imageUrl: part.imageUrl,
						specNo: part.specNo,
						totalStock: displayStock,
						inboundTotal: part.inboundTotal || 0,
						outboundTotal: part.outboundTotal || 0,
						netStock: part.netStock,
						transactionCount: part.transactions.length,
						recentTransactions: part.transactions
							.sort((a, b) => new Date(b.date) - new Date(a.date))
							.slice(0, 3),
						calculation: `入库${part.inboundTotal || 0} - 出库${part.outboundTotal || 0} = ${part.netStock}`,
						stockStatus: this.getStockStatus(displayStock)
					};
				});
				
				// 步骤6: 搜索过滤
				let filteredParts = spareParts;
				if (this.searchKeyword.trim()) {
					const keyword = this.searchKeyword.toLowerCase();
					filteredParts = spareParts.filter(part => {
						return part.name.toLowerCase().includes(keyword) ||
							   part.partNo.toLowerCase().includes(keyword) ||
							   part.type.toLowerCase().includes(keyword);
					});
				}
				
				// 步骤7: 排序（低库存优先）
				filteredParts.sort((a, b) => {
					if (a.totalStock === 0 && b.totalStock > 0) return -1;
					if (b.totalStock === 0 && a.totalStock > 0) return 1;
					return a.totalStock - b.totalStock;
				});
				
				// 步骤8: 限制显示数量
				this.spareParts = filteredParts.slice(0, 50);
				
				return Promise.resolve();
				
			} catch (error) {
				console.error('备件台账加载失败:', error);
				uni.showToast({
					title: '加载备件失败',
					icon: 'none',
					duration: 3000
				});
				
				this.spareParts = [];
				return Promise.reject(error);
			}
		},
		
		// 库存状态
		getStockStatus(netStock) {
			if (netStock === 0) {
				return 'empty';
			}
			if (netStock <= 5) {
				return 'low';
			}
			return 'normal';
		},
		
		// 备件类型映射
		getTypeName(code) {
			return this.typeMapping[code] || code || '未知类型';
		},
		
		// 加载字典
		loadDicts() {
			getDicts('part_status').then(r => {
				this.statusDict = r.data || r || [];
			}).catch(e => {
				console.warn('字典加载失败:', e);
			});
		},
		
		// 搜索
		onSearchInput() {
			clearTimeout(this.debounceTimer);
			this.debounceTimer = setTimeout(() => this.fetchList(), 500);
		},
		
		// 清空搜索
		clearSearch() {
			this.searchKeyword = '';
			this.fetchList();
		},
		
		// 手动刷新
		async manualRefresh() {
			this.isRefreshing = true;
			await this.fetchList();
			this.isRefreshing = false;
			uni.showToast({
				title: '刷新完成',
				icon: 'success',
				duration: 1500
			});
		},
		
		// 跳转新增（使用编辑页面，不传partNo即为新增）
		goAdd() {
			uni.navigateTo({
				url: '/pages/spare-parts/edit'
			});
		},
		
		// 查看详情
		viewDetail(item) {
			uni.navigateTo({
				url: `/pages/spare-parts/detail?partNo=${item.partNo}`
			});
		},
		
		// 删除备件
		async deletePart(partNo) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除此备件吗？此操作不可恢复。',
				success: async (res) => {
					if (res.confirm) {
						try {
							const result = await delPart(partNo);
							if (result.code === 200) {
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
								await this.fetchList();
							} else {
								uni.showToast({
									title: result.msg || '删除失败',
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('删除失败:', error);
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		// 交易类型显示
		getTransactionType(direction) {
			const map = {
				'IN': '入库',
				'INBOUND': '入库',
				'PURCHASE': '采购入库',
				'OUT': '出库',
				'OUTBOUND': '出库',
				'REPAIR': '维修出库',
				'TRANSFER': '调拨出库',
				'SCRAP': '报废出库',
				'MAINTENANCE': '维护出库'
			};
			return map[direction] || direction || '未知';
		},
		
		// 格式化日期
		formatDate(dateStr) {
			if (!dateStr) {
				return '';
			}
			try {
				const date = new Date(dateStr);
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit'
				});
			} catch (e) {
				return dateStr.substring(0, 16);
			}
		}
	},
	onPullDownRefresh() {
		this.manualRefresh().finally(() => {
			uni.stopPullDownRefresh();
		});
	},
	onReachBottom() {
		console.log('滚动到底部 - 可实现分页加载');
	}
};
</script>

<style lang="scss">
.container {
	min-height: 100vh;
	background: #F5F5F5;
}

.action-btn {
	width: 70rpx;
	height: 70rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: rgba(255, 255, 255, 0.3);
	border-radius: 50%;
	transition: all 0.2s;
	
	&:active {
		background: rgba(255, 255, 255, 0.5);
		transform: scale(0.95);
	}
}

.btn-icon {
	font-size: 40rpx;
	color: black;
	font-weight: bold;
}

/* 搜索栏 */
.search-section {
	display: flex;
	align-items: center;
	padding: 20rpx 30rpx;
	background: white;
}

.search-box {
	flex: 1;
	display: flex;
	align-items: center;
	background: #F5F5F5;
	border-radius: 50rpx;
	padding: 0 30rpx;
	height: 80rpx;
}

.search-icon {
	font-size: 32rpx;
	margin-right: 20rpx;
	color: #999;
}

.search-input {
	flex: 1;
	font-size: 28rpx;
	height: 80rpx;
	line-height: 80rpx;
}

.clear-icon {
	font-size: 32rpx;
	color: #999;
	padding: 10rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* 备件卡片列表 */
.parts-list {
	padding: 0 30rpx 30rpx;
}

.part-card {
	display: flex;
	background: white;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	transition: transform 0.2s;
	
	&:active {
		transform: scale(0.98);
	}
}

/* 左侧图片区域 */
.card-image {
	width: 200rpx;
	height: 200rpx;
	flex-shrink: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
	overflow: hidden;
	background: #f5f5f5;
}

.part-img {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

/* 右侧内容 */
.card-content {
	flex: 1;
	padding: 24rpx;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.card-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 16rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.card-info {
	display: flex;
	flex-direction: column;
	gap: 12rpx;
}

.info-row {
	display: flex;
	align-items: center;
	font-size: 26rpx;
}

.info-label {
	color: #999;
	min-width: 140rpx;
}

.info-value {
	color: #666;
	flex: 1;
}

.stock-value {
	color: #2196F3;
	font-weight: bold;
	font-size: 28rpx;
}

/* 空状态 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 200rpx 40rpx;
	text-align: center;
}

.empty-icon {
	font-size: 120rpx;
	margin-bottom: 30rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
	margin-bottom: 40rpx;
}

.empty-btn {
	background: #5B9FFE;
	color: white;
	border-radius: 40rpx;
	padding: 20rpx 60rpx;
	font-size: 28rpx;
}

/* 加载状态 */
.loading-state {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 100rpx 0;
}

.loading-text {
	font-size: 28rpx;
	color: #999;
}
</style>
